<?php
namespace plugins\finance\job;
use think\queue\Job;
use cmf\controller\PluginAdminBaseController;
use think\Model;
use think\log;
use think\Db;
use plugins\finance\model\FinanceRechargeModel;
use plugins\finance\model\FinanceModel;
use plugins\finance\model\FinanceAccountsModel;

class FinanceStatus{
	public function modifyStatus( $data )
	{
		if( isset( $data [ 'status' ] ) && $data [ 'status' ] === 'success' ){
			//判断订单属于哪一项
			$arr = explode('_', $data['out_trade_no']);
			$result = $this->$arr[1]($data);

		}else{
            //错误数据移出队列;
            // $job->delete();
        }
	}

	//充值
	private function recharge( $data ){
		db('test')->insert(['content'=>json_encode($data),'time'=>date('Y-m H:i:s',time()),'remark'=>'参数']);
		//充值记录
		$recharge = ( new FinanceRechargeModel )->get(['recharge_num'=>$data['out_trade_no']]);
		
		if($recharge == null){
			db('test')->insert(['content'=>'没有该记录','time'=>date('Y-m H:i:s',time()),'remark'=>'']);
			return false;
		}

		if($recharge->status != 1){
			db('test')->insert(['content'=>'记录状态错误','time'=>date('Y-m H:i:s',time()),'remark'=>'']);
			return false;
		}


		Db::startTrans();
		try{
			$remark = json_decode($data['remark'],true);

			//充值金额
			switch ($recharge->recharge_aim) {
				case 'wechatpay':
					$money = $remark['total_fee'] / 100;
					break;
				case 'alipay':
					$money = $remark['total_amount'];
					break;
				default:
					return false;
					break;
			}

			//修改充值记录为已充值
			$result1 = $recharge->save(['status'=>2]);

			//用户财务账户
			$finance = ( new FinanceModel )->get(['finance_id'=>$recharge->finance_id]);

			//增加用户账户金额
			$finance->balance = $finance->balance + $money;
			$result2 = $finance->save();

			//生成充值流水
			$FinanceAccountsModel = new FinanceAccountsModel;
			$result3 = ( new FinanceAccountsModel )->behavior(103,['member'=>$finance->finance_id,'remark'=>'余额充值','money'=>$money]);

			//生成用户提醒

			if($result1 && $result2 && $result3){
				Db::commit();
				return true;
			}else{
				return false;
			}


		}catch(\Exception $e){
        	Db::rollback();
        	db('test')->insert(['content'=>$e->getMessage(),'time'=>date('Y-m H:i:s',time()),'remark'=>'执行错误']);
        	return false;
		}

		


		

	}

}